/*
 * Copyright (C) 2017, Megatron King
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.github.megatronking.svg.generator.writer.impl;


import com.github.megatronking.svg.generator.render.VectorRenderer;
import com.github.megatronking.svg.generator.utils.Dimen;
import com.github.megatronking.svg.generator.vector.model.Vector;
import com.github.megatronking.svg.generator.writer.JavaClassWriter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SVGRendererTemplateWriter extends JavaClassWriter {

    private static final int METHOD_RENDER_MAX_LINE = 1000;

    private List<SplitMethod> mRenderSplitMethods = new ArrayList<>();

    private VectorRenderer mRenderer;
    private Vector mVector;

    public SVGRendererTemplateWriter(VectorRenderer renderer, Vector vector) {
        this.mRenderer = renderer;
        this.mVector = vector;
        setClassRelation("SVGRenderer", null);
    }

    @Override
    protected void writeImports(BufferedWriter bw) throws IOException {
        super.writeImports(bw);
        bw.write("import android.content.Context;");
        bw.newLine();
        bw.write("import android.graphics.Canvas;");
        bw.newLine();
        bw.write("import android.graphics.ColorFilter;");
        bw.newLine();
        bw.write("import android.graphics.Paint;");
        bw.newLine();
        bw.newLine();
        bw.write("import com.github.megatronking.svg.support.SVGRenderer;");
        bw.newLine();
        bw.newLine();
    }

    @Override
    protected void writeClassComment(BufferedWriter bw) throws IOException {
        super.writeClassComment(bw);
        bw.write("/**");
        bw.newLine();
        bw.write(" * AUTO-GENERATED FILE.  DO NOT MODIFY.");
        bw.newLine();
        bw.write(" * ");
        bw.newLine();
        bw.write(" * This class was automatically generated by the");
        bw.newLine();
        bw.write(" * SVG-Generator. It should not be modified by hand.");
        bw.newLine();
        bw.write(" */");
    }

    @Override
    protected void writeFields(BufferedWriter bw) throws IOException {
    }

    @Override
    protected void writeConstructMethods(BufferedWriter bw) throws IOException {
        bw.newLine();
        bw.write(HEAD_SPACE + "public " + mClassSimpleName + "(Context context) {");
        bw.newLine();
        bw.write(HEAD_SPACE + HEAD_SPACE + "super(context);");
        bw.newLine();
        bw.write(HEAD_SPACE + HEAD_SPACE + "mAlpha = " + mVector.alpha + "f;");
        bw.newLine();
        bw.write(HEAD_SPACE + HEAD_SPACE + "mWidth = " + getDimenSize(mVector.width) + ";");
        bw.newLine();
        bw.write(HEAD_SPACE + HEAD_SPACE + "mHeight = " + getDimenSize(mVector.height) + ";");
        bw.newLine();
        bw.write(HEAD_SPACE + "}");
        bw.newLine();
    }

    @Override
    protected void writeMethods(BufferedWriter bw) throws IOException {
        writeMethodRender(bw);
    }

    private void writeMethodRender(BufferedWriter bw) throws IOException {
        bw.newLine();
        bw.write(HEAD_SPACE + "@Override");
        bw.newLine();
        bw.write(HEAD_SPACE + "public void render(Canvas canvas, int w, int h, ColorFilter filter) {");
        bw.newLine();
        writeRendererContent(bw);
        bw.newLine();
        bw.write(HEAD_SPACE + "}");
        bw.newLine();
        for (SplitMethod splitMethod : mRenderSplitMethods) {
            bw.newLine();
            bw.write(HEAD_SPACE + "private void renderSplitMethod" + splitMethod.index +
                    "(Canvas canvas, ColorFilter filter, float scaleX, float scaleY) {");
            bw.newLine();
            bw.write(splitMethod.methodContent);
            bw.newLine();
            bw.write(HEAD_SPACE + "}");
            bw.newLine();
        }
    }

    private void writeRendererContent(BufferedWriter bw) throws IOException {
        String content = mRenderer.renderResult();
        int methodLineCount = calculateStringLineCount(content);
        // not support split method when contains 'getSegment'
        if (methodLineCount <= METHOD_RENDER_MAX_LINE || content.contains("getSegment")) {
            bw.write(content);
        } else {
            bw.write(substringByLineCount(content, 0, METHOD_RENDER_MAX_LINE));
            bw.newLine();
            for (int i = 1; i * METHOD_RENDER_MAX_LINE < methodLineCount; i++) {
                bw.write(HEAD_SPACE + HEAD_SPACE + "renderSplitMethod" + i + "(canvas, filter, scaleX, scaleY);");
                bw.newLine();
                int endLine = Math.min((i + 1) * METHOD_RENDER_MAX_LINE, methodLineCount);
                mRenderSplitMethods.add(new SplitMethod(i, substringByLineCount(content, i * METHOD_RENDER_MAX_LINE, endLine)));
            }
        }
    }

    private int calculateStringLineCount(String s) {
        int lineCount = 0;
        for (int i = 0; i < s.length(); i ++) {
            if ('\n' == s.charAt(i)) {
                lineCount++;
            }
        }
        return lineCount;
    }

    private String substringByLineCount(String s, int startLine, int endLine) {
        String[] lines = s.split("\n");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {
            if (i >= startLine && i < endLine) {
                sb.append(lines[i]).append("\n");
            }
        }
        return sb.toString();
    }

    private String getDimenSize(String size) {
        if (Dimen.isDip(size)) {
            return "dip2px(" + Dimen.convert(size) + "f)";
        } else if (Dimen.isPx(size)) {
            return "(int)" + Dimen.convert(size) + "f";
        } else {
            return "0f";
        }
    }

    private static class SplitMethod {

        private SplitMethod(int index, String methodContent) {
            this.index = index;
            this.methodContent = methodContent;
        }

        private int index;
        private String methodContent;

    }
}
